<template>
  <div class="article">
    <div v-if="showIframe" class="iframe-modal">
      <div class="iframe-background" @click="closeIframe"></div>
      <div class="ad-container">
        <div class="close-btn" @click="closeIframe">
          <div class="close-btn-text"></div>
        </div>
        <iframe
          class="ad-iframe"
          src="https://tnaot.com/ad5.html"
          frameborder="0"
        ></iframe>
      </div>
    </div>

    <IndexHeader />
    <div class="container-m">
      <div class="news_title">
        <h1>{{ newsDetail.title }}</h1>
        <div class="news_info">
          <span>{{ newsDetail.author }}</span>
          <span>{{
            newsDetail.release_timestamp | dateFtt('yyyy-MM-dd hh:mm:ss')
          }}</span>
        </div>
      </div>
      <div class="news-content">
        <div ref="newsContent" v-html="newsDetail.content"></div>

        <div
          class="ad-box"
          style=" width:auto; margin: 0 auto; text-align:center;"
        >
          <iframe
            frameborder="0"
            scrolling="no"
            style="width: 355px; height: 270px; overflow: hidden;  margin-left: 0px;  "
            class="ad-iframe"
            src="https://tnaot.com/adpcmr1.html"
          ></iframe>
        </div>
      </div>

      <div
        v-if="articleBanner && articleBanner.imageUrl && !hiddenAd"
        ref="adRef"
        class="wrapper-ad"
        :style="{ height: `${screenHeight}px` }"
      >
        <div
          class="ad"
          :style="{
            clip: `rect(10000px, ${screenWidth}px, 20000px, 0)`,
            height: `${screenHeight}px`
          }"
        >
          <div
            v-if="isVideoAd"
            class="video-wrap"
            @click.stop="jumpPage(articleBanner)"
          >
            <div
              class="video-background"
              :style="{
                background: `url(${articleBanner.imageUrl})`,
                'background-size': 'cover'
              }"
            ></div>
            <button
              class="mute"
              id="mute"
              type="button"
              data-state="unmute"
              @click.stop="onSwitchMute()"
              style="display: block;"
            >
              Mute/Unmute
            </button>
            <video
              class="video"
              autoplay
              muted
              loop
              controlslist="nodownload nofullscreen noremoteplayback"
              webkit-playsinline="true"
              x-webkit-airplay="true"
              playsInline="{true}"
              x5-playsinline="true"
              x5-video-orientation="portraint"
              :src="articleBanner.video"
            ></video>
          </div>
          <img
            v-else
            class="cover"
            :src="articleBanner.imageUrl"
            :style="{ height: `${screenHeight}px` }"
            @click="jumpPage(articleBanner)"
          />
        </div>
      </div>

      <!-- 免责声明 -->
      <div class="liability-tip">
        <p class="liability-tip-label">{{ newsDetail.statementTitle }}</p>
        <p class="liability-tip-desc">{{ newsDetail.statement }}</p>
      </div>
      <!-- 疫情 -->
      <Gather></Gather>
    </div>

    <div class="Recommend">
      <div class="Recommend-title">
        <h2>{{ $t('Best_recommend') }}</h2>
        <Banner
          v-if="JSON.stringify(banner) != '{}' && banner != null"
          :banner="banner"
        />
      </div>
      <!-- 列表 -->
      <Recommend :relatedList="relatedList" />
    </div>
  </div>
</template>

<script>
import IndexHeader from '@/components/m/Header.vue';
import Banner from '@/components/m/Banner.vue';
import Recommend from '@/components/m/Recommend.vue';
import Gather from '@/components/m/Gather.vue';
import { LRUcache } from '@/utils/lru_cache.js';
import { getBannerListApi } from '@/ajax/service';
import reportMixin from '@/mixins/report';

export default {
  mixins: [reportMixin],

  components: {
    IndexHeader,
    Banner,
    Recommend,
    Gather
  },

  data() {
    return {
      newsDetail: {},
      showBanner: false, //是否显示金币提示
      banner: {}, //banner内容
      relatedList: [], //精彩推荐
      articleBanner: {},
      xTop: 0,
      adDom: '',
      hiddenAd: false,
      isFirstScreenShow: false,
      isVideoAd: false,
      showIframe: true
    };
  },

  head() {
    const article = this.newsDetail;
    return this.$getArticleSeoHead(article);
  },

  async asyncData(ctx) {
    try {
      /* 404处理 */
      function toError() {
        ctx.error({
          statusCode: 404,
          message: 'Post not found'
        });
        return;
      }
      /* 有缓存，取缓存，无缓存，请求接口 */
      const id = ctx.params.id.replace(/\.html$/, '');
      let bannerObjData = LRUcache.get(
          `/${ctx.store.state.locale}/article/get_banner_channel?imageType=1`
        ),
        resultObjData = LRUcache.get(
          `/${ctx.store.state.locale}/article/get_news_detail?news_id=${id}&news_type=1`
        ),
        relatedObjData = LRUcache.get(
          `/${ctx.store.state.locale}/get_related_list/1/${id}`
        );
      let banner, resultObj, related;
      if (bannerObjData && bannerObjData.result) {
        banner = bannerObjData;
      } else {
        banner = await ctx.$axios.$get(
          `/article/get_banner_channel?imageType=1`
        );
        !banner.result && toError();
        LRUcache.set(
          `/${ctx.store.state.locale}/article/get_banner_channel?imageType=1`,
          banner
        );
      }

      if (resultObjData && resultObjData.result) {
        resultObj = resultObjData;
      } else {
        resultObj = await ctx.$axios.$get(
          `/article/get_news_detail?news_id=${id}&news_type=1`
        );
        !resultObj.result && toError();
        LRUcache.set(
          `/${ctx.store.state.locale}/article/get_news_detail?news_id=${id}&news_type=1`,
          resultObj
        );
      }

      if (relatedObjData && relatedObjData.result) {
        related = relatedObjData;
      } else {
        related = await ctx.$axios.$get(
          `/article/get_related_list?news_id=${id}&news_type=1`
        );
        !related.result && toError();
        LRUcache.set(
          `/${ctx.store.state.locale}/get_related_list/1/${id}`,
          related
        );
      }

      const { result: articleBanner = [] } = await getBannerListApi({
        lan: ctx.store.getters.localeFull,
        sourceType: 20
      });

      // 匹配当前作者的banner
      const authorId = resultObj.result.member_id;
      const currentBanner = articleBanner.filter(
        item => item.authorId == authorId
      );

      return {
        newsDetail: resultObj.result,
        showBanner: banner.result.isOpenCoin,
        banner: banner.result.banner_list,
        relatedList: related.result,
        articleBanner: currentBanner[0] || {}
      };
    } catch (err) {
      ctx.error({ statusCode: 404, message: '网络异常，请重试！' });
    }
  },

  computed: {
    screenHeight() {
      try {
        return document.documentElement.clientHeight;
      } catch {
        return 0;
      }
    },
    screenWidth() {
      try {
        return document.documentElement.clientWidth;
      } catch {
        return 0;
      }
    },

    domHeight() {
      if (this.$refs.adRef) {
        const height = window.getComputedStyle(this.$refs.adRef).height;
        return Math.ceil(height.slice(0, -2));
      }
    }
  },

  mounted() {
    this.$nextTick(() => {
      document.addEventListener('scroll', this.scroll);
      setTimeout(() => {
        this.insertBanner();
        this.modifyHref();
      }, 500);
    });

    const that = this;
    this.randomNumber = new Date().getTime();
    setTimeout(() => {
      that.closeIframe();
    }, 6500);
  },

  destroyed() {
    document.removeEventListener('scroll', this.scroll);
  },

  methods: {
    closeIframe() {
      this.showIframe = false;
    },
    modifyHref() {
      const fatherDom = this.$refs.newsContent;
      const as = fatherDom.querySelectorAll('a[data-value]');
      if (!as || as.length === 0) return;

      as.forEach(dom => {
        const query =
          dom.href
            .split('?')[1]
            .split('&')
            .reduce((p, t) => {
              const [key, value] = t.split('=');
              p[key] = value;
              return p;
            }, {}) || {};

        if (query.link) {
          dom.href = query.link;
        }
      });
    },

    scroll() {
      if (this.hiddenAd) return;

      const scrollTop =
        window.pageXOffset ||
        document.documentElement.scrollTop ||
        document.body.scrollTop;

      // 广告高度domHeight 屏幕高度 screenHeight
      const { screenHeight, screenWidth, domHeight, isFirstScreenShow } = this;

      // x 插入位置距离文档流顶部的高度
      const { xTop } = this;

      // 垂直方向 显示广告的起点相对屏幕顶点的距离
      const top = Math.ceil(xTop - scrollTop);

      // 垂直方向 显示广告的终点相对屏幕顶点的距离
      let bottom;

      // 广告不可见
      if (scrollTop + screenHeight <= xTop) {
        bottom = 0;
      }
      // 广告已划过
      else if (scrollTop >= xTop + domHeight) {
        bottom = 0;
        this.maybeReportPv();
      } else {
        // 广告可见一部分
        bottom = xTop + domHeight - scrollTop;
        this.maybeReportPv();
      }

      const styleObj =
        scrollTop > 0 || isFirstScreenShow
          ? {
              clip: `rect(${top}px, ${screenWidth}px, ${bottom}px, -20px)`
            }
          : {
              clip: `rect(10000px, ${screenWidth}px, 20000px, 0)`
            };

      if (this.adDom) {
        this.adDom.children[0].style.clip = styleObj.clip;
      }
    },

    maybeReportPv() {
      if (!this.$reportedAdPv) {
        this.$reportedAdPv = true;
        this.report('ad_Banner_1', {
          ad_id: this.articleBanner.id,
          position: 5
        });
      }
    },

    insertBanner() {
      const { articleBanner, newsDetail } = this;

      // 当前作者才显示
      if (
        !articleBanner ||
        !newsDetail ||
        articleBanner.authorId != newsDetail.member_id
      ) {
        this.hiddenAd = true;
        return;
      }

      this.isVideoAd = !!articleBanner.video;

      const ref = this.$refs.newsContent;
      const newNode = this.$refs.adRef;
      this.adDom = newNode;

      // 图文内容小于一屏 不插入广告
      const newsHeight = Math.ceil(
        window.getComputedStyle(ref).height.slice(0, -2)
      );
      const isLessThanOneScreen = newsHeight <= this.screenHeight;
      if (isLessThanOneScreen) {
        this.hiddenAd = true;
        return;
      }

      // 只有一个段落 不插入广告
      const len = ref.children.length;
      if (len < 2) {
        this.hiddenAd = true;
        return;
      }
      const nextNode = ref.children[len - 1];

      // 如果是在旧页面刷新 相对视口的位置可能为负值, 所以需要加上滚动距离，得到距离文档顶部的距离
      const top = Math.ceil(nextNode.getBoundingClientRect().top);
      const scrollTop =
        window.pageXOffset ||
        document.documentElement.scrollTop ||
        document.body.scrollTop;
      this.xTop = top + scrollTop;

      // 首屏展示广告
      this.isFirstScreenShow = this.xTop < this.screenHeight;

      this.scroll();
      ref.insertBefore(newNode, nextNode);
    },

    onSwitchMute() {
      const video = this.adDom.querySelector('.video');
      const mute = this.adDom.querySelector('.mute');
      const state = mute.dataset.state;
      mute.dataset.state = state == 'unmute' ? 'mute' : 'unmute';
      video.muted = !video.muted;
    },

    jumpPage({ url, pageType, type }) {
      if (pageType != 4 || type === 3) return;
      this.report('ad_Banner_2', { ad_id: this.articleBanner.id, position: 5 });
      window.open(url);
    }
  }
};
</script>

<style lang="scss" scoped>
.article {
  .liability-tip {
    color: rgba(12, 12, 28, 0.7);
    margin: 0 0 20px 0;
  }

  .liability-tip-label {
    font-size: 24px;
    font-weight: bold;
    margin: 0 0 8px 0;
  }

  .liability-tip-desc {
    font-size: 24px;
    line-height: 1.6;
  }

  .news-content {
    img {
      border-radius: 8px;
    }
  }
}

.wrapper-ad {
  margin: 0 0 24px 0;
  z-index: 999999;
}

.cover {
  width: 100%;
  object-fit: cover;
}

.ad {
  position: fixed;
  right: 0;
  left: 0;
  top: 0;
  bottom: 0;
  overflow: hidden;
  z-index: 99998;
  padding: 0;
  margin: 0;
  width: 100%;
}

.video-wrap {
  width: 100%;
  height: 100%;
  position: relative;

  .video-background {
    width: 100%;
    height: 100%;
    background-size: cover;
    position: absolute;
    top: 0;
    left: 0;
  }

  .video {
    width: 80%;
    height: auto;
    max-width: 660px;
    position: absolute;
    top: 12%;
    left: 0;
    right: 0;
    margin: 0 auto;
    opacity: 1;
  }

  #mute {
    text-align: center;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    border: none;
    cursor: pointer;
    text-indent: -99999px;
    background-color: rgba(0, 0, 0, 0);
    background-size: 40px auto;
    background-repeat: no-repeat;
    width: 60px;
    height: 60px;
    font-size: 20px;
    border-radius: 50%;
    background-position: center;
    position: absolute;
    top: 20px;
    right: 30px;
    outline: none;
    border: none;
  }

  button#mute[data-state='mute'] {
    background-image: url('');
  }

  button#mute[data-state='unmute'] {
    background-image: url('');
  }
}

.iframe-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9999;

  .ad-container {
    width: 150%;
    height: 1111px;
    // background: white url('~assets/images/download_app.png') center/cover
    //   no-repeat;
    position: relative;
    z-index: 1;
    cursor: pointer;
    .ad-iframe {
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      margin: auto;
      width: 100%;
      height: 100%;
      background-color: #fff;
    }

    .close-btn {
      position: absolute;
      bottom: -8px;
      right: 50%;
      margin-left: 30px;
      width: 60px;
      height: 60px;
      line-height: 60px;
      text-align: center;
      background: rgba(0, 0, 0, 0);
      color: white;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 24px;
      cursor: pointer;
      z-index: 2;
    }

    .ad-content {
      width: 100%;
      height: 100%;
    }
  }
}
</style>
